module.exports = (sequelize, DataTypes) => {
  const SudokuAnswer = sequelize.define('SudokuAnswer', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: '主键ID'
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      field: 'user_id',  // 映射到数据库字段
      comment: '用户ID'
    },
    puzzleId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      field: 'puzzle_id',  // 映射到数据库字段
      comment: '题目ID',
      references: {
        model: 'sudoku_puzzles',
        key: 'id'
      }
    },
    answer: {
      type: DataTypes.STRING(81),
      allowNull: false,
      comment: '用户提交的答案（完成时为最终答案，暂存时为当前进度）'
    },
    isCorrect: {
      type: DataTypes.BOOLEAN,
      allowNull: true,
      defaultValue: null,
      field: 'is_correct',
      comment: '是否正确（完成时设置，暂存时为NULL）'
    },
    timeUsed: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      field: 'time_used',
      comment: '用时（秒）'
    },
    mistakes: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '错误次数'
    },
    hintsUsed: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      field: 'hints_used',
      comment: '使用提示次数'
    },
    startedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      field: 'started_at',
      comment: '开始时间'
    },
    finishedAt: {
      type: DataTypes.DATE,
      allowNull: true,
      defaultValue: null,
      field: 'finished_at',
      comment: '完成时间（NULL表示未完成，仅暂存）'
    },
    creator: {
      type: DataTypes.STRING(64),
      allowNull: true,
      comment: '创建人'
    },
    modifier: {
      type: DataTypes.STRING(64),
      allowNull: true,
      comment: '修改人'
    },
    isDeleted: {
      type: DataTypes.CHAR(1),
      defaultValue: '0',
      field: 'is_deleted',  // 映射到数据库的实际字段名
      comment: '是否删除（0-未删，1-已删）'
    }
  }, {
    tableName: 'sudoku_answers',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'modified_at',
    indexes: [
      {
        unique: true,
        fields: ['userId', 'puzzleId', 'isDeleted'],
        name: 'unique_user_puzzle'
      },
      {
        fields: ['userId']
      },
      {
        fields: ['puzzleId']
      },
      {
        fields: ['isCorrect']
      },
      {
        fields: ['isDeleted']
      }
    ]
  });

  return SudokuAnswer;
};
